import React, { useMemo } from 'react';
import { List, Button, Skeleton } from 'antd';
import loadable from '@loadable/component';

import styles from './index.module.scss';

const COMP = {
    tabmerch: loadable(() => import('../MerchItem'), { fallback: <Skeleton style={{padding:6}} active /> }),
    merch: loadable(() => import('../MerchItem'), { fallback: <Skeleton style={{padding:6}} active /> }),
    mymerch: loadable(() => import('../MerchItem'), { fallback: <Skeleton style={{padding:6}} active /> }),
    mycontrib: loadable(() => import('../MyContribItem'), { fallback: <Skeleton style={{padding:6}} active /> }),
};

/*
    列表组件
    props:
        dataSource: 列表数据
        loading: 是否加载中
        className: 自定义类名
        type: 列表类型
        pagination: 分页配置 和 (showMore,onLoadMore) 二选一
        showMore: 是否显示加载更多按钮
        onLoadMore: 加载更多回调
*/
export default props => {
    const { dataSource=[], loading, className, type, grid=null, pagination=null, showMore, onLoadMore } = props;
    const Comp = COMP[type] || COMP.merch;
    const defaultGrid = { gutter: [
        { xs: 8, sm: 8, md: 16, lg: 16, xl: 16 },
        { xs: 0, sm: 0, md: 0, lg: 0, xl: 0 }
    ], xs: 2, sm: 2, md: 3, lg: 3, xl: 4 };

    const loadMore = showMore ?
        <div className={styles['load-more']}>
            <Button loading={loading} onClick={onLoadMore}>加载{loading ? '中...' : '更多'}</Button>
        </div>
        :
        null;

    const listProps = useMemo(() => {
        const obj = {grid: defaultGrid, pagination: false};
        if(grid) obj['grid'] = grid;
        if(pagination) {
            obj['pagination'] = {...pagination, position: 'bottom', align: 'center'};
        }else{
            obj['loadMore'] = loadMore;
        }
        return obj;
    }, [pagination, grid, showMore]);

    return (
        <List
            className={`${styles['container']} ${className}`}
            dataSource={dataSource}
            renderItem={item => (
                <List.Item>
                    <Comp item={item} type={type || 'merch'} />
                </List.Item>
            )}
            loading={loading}
            {...listProps}
        />
    );
};
